NTRIP_BUF_MAX=2048
local libnet = require "libnet"
local gps_uart_id = 2

libgnss.clear() -- 清空数据,兼初始化

uart.setup(gps_uart_id, 115200)
uart.setup(0, 115200, 8, 1, uart.NONE)

uart.on(0, "receive", function(id, len)
    local data = uart.read(id, len, com_buff)
    log.info("uart0:", data)
    --uart.write(0, data)
end)


sys.taskInit(function()
    -- Air780EG工程样品的GPS的默认波特率是9600, 量产版是115200,以下是临时代码
    log.info("GPS", "start")
    -- 绑定uart,底层自动处理GNSS数据
    -- 第二个参数是转发到虚拟UART, 方便上位机分析
    libgnss.bind(gps_uart_id)
    -- libgnss.on("raw", function(data)
    --     sys.publish("mqtt_pub", "/gnss/" .. mobile.imei() .. "/up/nmea", data, 1)
    -- end)
    
    uart.write(gps_uart_id, "$PAIR432,1*22\r\n")
    uart.write(gps_uart_id, "$PAIR434,1*24\r\n")
    uart.write(gps_uart_id, "$PAIR436,1*26\r\n")
    libgnss.on("raw", function(data)
        uart.write(1, data)
    end)
    sys.wait(200) -- GPNSS芯片启动需要时间

    -- 调试日志,可选
    --libgnss.debug(true)
--    while true do
--        uart.tx(0, "hello tx", 0, 8)
 --       uart.write(0, "hello write")
 --       sys.wait(1000)
 --   end
end)

function upload_stat()
    -- 发送数据包
    --local msg = {libgnss.isFix(), os.time()}
    local rmc = libgnss.getRmc(1)
    local gga = libgnss.getGga(0)
    --local gsa = libgnss.getGsa()
    --local vtg = libgnss.getVtg()
    --table.insert(msg, rmc.lng)
    --table.insert(msg, rmc.lat)
    --local gll = libgnss.getGll()
    --table.insert(msg, 0) -- altitude
    --table.insert(msg, 0) -- azimuth
    --table.insert(msg, (vtg and vtg.speed_kph) and vtg.speed_kph or 0) -- speed
    --table.insert(msg, 0) -- sateCno
    --table.insert(msg, 0) -- sateCnt
    -- jdata.msg = msg
    -- local data = json.encode({msg=msg})
    -- log.info("report", rmc.year, rmc.month, rmc.day, rmc.hour,rmc.min,rmc.sec)
    local str = string.format("%02d%02d%02d%02d%02d%02d", rmc.year % 100,
                              rmc.month, rmc.day, rmc.hour, rmc.min, rmc.sec)
    --log.info("time:", str)
    pvt_set(rmc.lat // 10, rmc.lng // 10, str, gga.altitude // 1, (rmc.speed * 18.52) // 1, rmc.course // 1)
	log.info("gga:", libgnss.getGga(3))
    uart.write(0, libgnss.getGga(3))
end

--sys.timerLoopStart(upload_stat, 1000)

function gnss_handler(event, ticks)
    -- event取值有
    -- FIXED 定位成功
    -- LOSE  定位丢失
    -- ticks是事件发生的时间,一般可以忽略
    -- log.info("gnss", "state", event, ticks)
    if event == "FIXED" then
        -- local locStr = libgnss.locStr()
        -- log.info("gnss", "locStr", locStr)
        --log.info("RMC", json.encode(libgnss.getRmc(2) or {}, "12f"))
        --log.info("GGA", json.encode(libgnss.getGga(2) or {}, "12f"))
        -- log.info("GGA", libgnss.getGga(3))
        gpio.set(GNSS_FLAG, gpio.HIGH)
    elseif event == "LOSE" then
        gpio.set(GNSS_FLAG, gpio.LOW)
    elseif event == "UPDATE" then
        log.info("PVT update")
        upload_stat()
        sys.publish("GNSS_UPDATE")

        local gga = libgnss.getGga(0)
        if gga.fix_quality >= 4 then
            gpio.set(GNSS_FLAG, gpio.HIGH)
        else
            gpio.toggle(GNSS_FLAG)
        end
        -- log.info("GGA", libgnss.getGga(3))
    end

    log.info("PVT", rtos.meminfo("lua"))
end
-- 订阅GNSS状态编码
sys.subscribe("GNSS_STATE", gnss_handler)

-- 对接ntrip服务器

ntrip_host="103.143.19.54"
ntrip_port=8002
ntrip_mp="RTCM33GRCEJ15"
ntrip_user="feng246"
ntrip_pw="46727"
ntrip_upgga=0

local ntripName = "ntriptask"
local ntrip_auth=""
local ntrip_recnt=1

function init_ntrip()
    local v = fdb.kv_get("nip")
    if v ~= nil and type(v) == "string" then
        ntrip_host=v
    end

    v = fdb.kv_get("nport")
    if v ~= nil and type(v) == "string" then
        ntrip_port=tonumber(v)
    end

    v = fdb.kv_get("nmp")
    if v ~= nil and type(v) == "string" then
        ntrip_mp=v
    end

    v = fdb.kv_get("nun")
    if v ~= nil and type(v) == "string" then
        ntrip_user=v
    end

    v = fdb.kv_get("npw")
    if v ~= nil and type(v) == "string" then
        ntrip_pw=v
    end

    v = fdb.kv_get("nup")
    if v ~= nil and type(v) == "string" then
        ntrip_upgga=tonumber(v)
    end

	auth_data = "GET /" .. ntrip_mp .. " HTTP/1.0\r\nUser-Agent: NTRIP cnostr ntrip\r\nAuthorization: Basic " .. crypto.base64_encode(ntrip_user .. ":" .. ntrip_pw) .. "\r\n\r\n"
    log.info(auth_data)
end

function ntriptask()
	local rx_buff = zbuff.create(NTRIP_BUF_MAX)
	local netc
	local result, param, succ
    local a,n,m
    local netc = socket.create(nil, ntripName)
	-- socket.debug(netc, true)
    local ticks = mcu.ticks()
	socket.config(netc, nil, nil, nil)
    while 1 do
        if ntrip_recnt then
            init_ntrip()
            ntrip_recnt=0
        end
        result = libnet.waitLink(ntripName, 0, netc)
		result = libnet.connect(ntripName, 15000, netc, ntrip_host, ntrip_port)

        if result then
			log.info("服务器连上了", "上报注册注册信息", auth_data)
			libnet.tx(ntripName, 0, netc, auth_data)
		end

        while result and ntrip_recnt == 0 do
			succ, param = socket.rx(netc, rx_buff)
			if not succ then
				log.info("服务器断开了", succ, param, ntrip_host, string.format("%d", ntrip_port))
				break
			end
			if rx_buff:used() > 0 then
				a=rx_buff:used()
				n = 0
				log.info("收到 RTK 数据，长度", string.format("%d", rx_buff:used()))
				while n < a do
					m=uart.tx(gps_uart_id, rx_buff, n, a - n)
					n=n+m
					log.info("send ", string.format("%d", n))
				end
                log.info("RTK", rtos.meminfo("lua"))

                --upload gga to cors
                
                if ntrip_upgga == 1 then
                    if mcu.ticks() - ticks > 5000 then
                        libnet.tx(ntripName, 0, netc, libgnss.getGga(3))
                        ticks = mcu.ticks()
                    end
                end
                
				--n = uart.write(gps_uart_id, rx_buff)

				--log.info("send ", string.format("%d", n))
				--rx_buff:seek(n)
				--n = uart.write(gps_uart_id, rx_buff)
				--log.info("send ", string.format("%d", n))
				--log.info("剩余", string.format("%d", rx_buff:used()))
				rx_buff:seek(0)
			end
			if rx_buff:len() > NTRIP_BUF_MAX then
				rx_buff:resize(NTRIP_BUF_MAX)
			end
			--uart.write(cmd_uart_id, "rdy\r\n")
            result, param = libnet.wait(ntripName, 15000, netc)
            if not result then
                log.info("服务器断开了", result, param)
                break
            end
			--log.info("sys", rtos.meminfo("sys"))
			--result, param = libnet.wait(ntripName, 1000, netc)
			--if not result then
			--	log.info("服务器断开了", result, param)
			--	break
			--end

            -- 发送数据包
            --if data then
                --libnet.tx(ntripName, 0, netc, data)
            --end
		end
		libnet.close(ntripName, 5000, netc)
		sys.wait(1000)
    end
end

function ntrip_reconnect()
    ntrip_recnt=1
end
local function ntripCB(msg)
	log.info("未处理消息", msg[1], msg[2], msg[3], msg[4])
end
--sysplus.taskInitEx(ntriptask, "ntriptask", ntripCB)


--sys.timerLoopStart(function() log.info("Mem Free Size:", 1024-collectgarbage("count")) end, 1000)
--[[
-- 对接服务器
local taskName = "gnsstask"
function gnsstask()
	local rx_buff = zbuff.create(1024)
	local netc
	local result, param, succ
    local ntrip_host, ntrip_port = "gps.nutz.cn", 19002
    local netc = socket.create(nil, taskName)
	-- socket.debug(netc, true)
	socket.config(netc, nil, nil, nil)
    while 1 do
        result = libnet.waitLink(taskName, 0, netc)
		result = libnet.connect(taskName, 15000, netc, ntrip_host, ntrip_port)
        local jdata = {
            imei = mobile.imei(),
            iccid = mobile.iccid()
        }
        if result then
            local data = json.encode(jdata)
			log.info("服务器连上了", "上报注册注册信息", data)
			libnet.tx(taskName, 0, netc, data)
		end
        while result do
			succ, param = socket.rx(netc, rx_buff)
			if not succ then
				log.info("服务器断开了", succ, param, ntrip_host, ntrip_port)
				break
			end
			if rx_buff:used() > 0 then
				log.info("收到服务器数据，长度", rx_buff:used())
				rx_buff:del()
			end
			if rx_buff:len() > 1024 then
				rx_buff:resize(1024)
			end
			a,b,c=rtos.meminfo("sys")
			log.info("sys", "meminfo", string.format("%d", a),string.format("%d", b), string.format("%d", c))
			result, param = libnet.wait(taskName, 1000, netc)
			if not result then
				log.info("服务器断开了", result, param)
				break
			end

            -- 发送数据包
            local msg = {libgnss.isFix(), os.time()}
            local rmc = libgnss.getRmc(1)
            local gsa = libgnss.getGsa()
            local vtg = libgnss.getVtg()
            table.insert(msg, rmc.lng)
            table.insert(msg, rmc.lat)
            local gll = libgnss.getGll()
            table.insert(msg, 0) -- altitude
            table.insert(msg, 0) -- azimuth
            table.insert(msg, (vtg and vtg.speed_kph) and vtg.speed_kph or 0) -- speed
            table.insert(msg, 0) -- sateCno
            table.insert(msg, 0) -- sateCnt
            --jdata.msg = msg
            local data = json.encode({msg=msg})
            log.info("report", data)
            if data then
                libnet.tx(taskName, 0, netc, data)
            end
			sys.wait(100)
		end
		d1Online = false
		libnet.close(taskName, 5000, netc)
			a,b,c=rtos.meminfo("sys")
			log.info("sys", "meminfo", string.format("%d", a),string.format("%d", b), string.format("%d", c))
		sys.wait(1000)
    end
end

local function netCB(msg)
	log.info("未处理消息", msg[1], msg[2], msg[3], msg[4])
end
sysplus.taskInitEx(gnsstask, "gnsstask", netCB)
-- sys.subscribe("NTP_UPDATE", function()
--     if not libgnss.isFix() then
--         -- "$AIDTIME,year,month,day,hour,minute,second,millisecond"
--         local date = os.date("!*t")
--         local str = string.format("$AIDTIME,%d,%d,%d,%d,%d,%d,000",
--                              date["year"], date["month"], date["day"], date["hour"], date["min"], date["sec"])
--         log.info("gnss", str)
--         uart.write(gps_uart_id, str .. "\r\n")
--     end
-- end)

-- if socket and socket.sntp then
--     sys.subscribe("IP_READY", function()
--         socket.sntp()
--     end)
-- end

-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
-- sys.run()之后后面不要加任何语句!!!!!
]] --
